const router = require('koa-router')()

const { register, userNameFilter } = require('../controller/users')
const { SuccessModel, ErrorModel } = require('../model/resModel')

router.prefix('/api/users')

router.post('/register', async function (ctx, next) {
  const { username, password } = ctx.request.body
  console.log(username, password)
  if (!username || !password) {
    ctx.body = new ErrorModel('用户名或者密码不能为空')
    return
  }
  const row = await userNameFilter(username)
  if (row) {
    ctx.body = new ErrorModel('用户名已存在')
    return
  }
  const data = await register(username, password)
  if (data.id) {
    ctx.body = new SuccessModel(data)
    return
  }
  ctx.body = new ErrorModel('注册失败，请检查用户名或密码')
})

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
